package com.bdqn.systems.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.enums.RoleStatusEnum;
import com.bdqn.exception.BusinessException;
import com.bdqn.response.ResultCode;
import com.bdqn.systems.entity.Role;
import com.bdqn.systems.mapper.RoleMapper;
import com.bdqn.systems.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.Naming;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author cp
 * @since 2020-11-30
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public Page<Role> findByName(String name,Page<Role> page) {
        List<Role> byName = this.baseMapper.findByName(page,name);
        return page.setRecords(byName);
    }

    @Override
    public boolean editRoleState(Integer id){
        Role role = this.baseMapper.selectById(id);
        role.setStatus(role.getStatus()==RoleStatusEnum.AVAILABLE.getStatusCode()?
                RoleStatusEnum.DISABLE.getStatusCode():
                RoleStatusEnum.AVAILABLE.getStatusCode());
        return this.updateById(role);
    }

    @Override
    public Integer getNotNullName(String name) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("role_name",name);
        Integer integer = this.baseMapper.selectCount(wrapper);
        if(integer<1){
            throw new BusinessException(ResultCode.ROLE_ALREADY_EXIST.getCode(),
                    ResultCode.ROLE_ALREADY_EXIST.getMessage());
        }
        return integer;
    }

    @Override
    public Integer insert(Role role) {
        this.getNotNullName(role.getRoleName());
        role.setStatus(RoleStatusEnum.AVAILABLE.getStatusCode());
        return this.baseMapper.insert(role);
    }

    @Override
    public void exportRoleExcel(HttpServletResponse response, List<Role> roles) throws IOException {

        //----- 写入excel文件
        String exportFileName = "角色列表.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), Role.class)
                .sheet("角色信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(roles);
    }

    @Override
    public List<Role> findRoleAll(String roleName) {
        return this.baseMapper.findByName(null, roleName);
    }

}
